package cn.ybz21.hibot.topic_process_center.app;

import cn.ybz21.hibot.bean.App;
import cn.ybz21.hibot.bean.AppState;
import cn.ybz21.hibot.db.service.AppDAO;
import cn.ybz21.hibot.topic_process_center.base.BaseCenter;
import cn.ybz21.hibot.util.StaticValues;
import cn.ybz21.hibot.util.shell.ShellExecutor;

import com.google.gson.Gson;
import com.ibm.micro.client.mqttv3.MqttMessage;
import com.ibm.micro.client.mqttv3.MqttTopic;

public class AppStopCenter implements BaseCenter {

	@Override
	public void doAction(MqttTopic topic, MqttMessage message) {
		System.out.println("---------------------\nstop app");
		System.out.println(message.toString());
		Gson gson = new Gson();
		App app = (App) gson.fromJson(message.toString(), App.class);
		process(app);
		System.out.println("end stop app\n---------------------");
	}

	void process(App app) {
		AppDAO dao = new AppDAO();
		app = dao.queryAppById(app.id);
		ShellExecutor.execLocal("sh " + StaticValues.SHELL_STOP_APP + " "
				+ app.pid,true);
//		Process process = AppStorage.getProcess(app.id);
//		if (process != null)
//			process.destroy();
//		if (process != null)
//			process.destroyForcibly();
		app.state = AppState.STOP;
		dao.updateAppState(app);
	}
}
